// pages/route/daily/daily.js
const app = getApp();
const service = require('../../../../utils/service.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 出发点列表
    goData: [],
    // 目的地列表
    destinationDate: [],
    // picker默认出发地列表
    startSpotList: [],
    startSpotListPreview: [],
    // picker默认目的地列表
    endSpotList: [],
    endSpotListPreview: [],
    // 选择的出发点
    startSpot: [],
    // 选择的目的地
    endSpot: [],
    // 选择的时间
    date: null,
    // 星期几
    weekday: null,
    // 时间选择器开始时间
    startDate: null,
    // 时间选择器结束时间
    endDate: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    options.pageName && wx.setNavigationBarTitle({
      title: options.pageName,
    });
    let date = new Date();
    this.loadData();
    this.setData({
      weekday: '星期' + app.utils.parseTime(date, '{a}'),
      date: app.utils.parseTime(date, '{y}-{m}-{d}'),
      startDate: app.utils.parseTime(date, '{y}-{m}-{d}'),
      endDate: app.utils.parseTime(date.getTime() + 2592000000, '{y}-{m}-{d}')
    });
  },

  // 加载首页数据
  loadData() {
    let that = this;
    service.getConnect(service.api.getDailyRouteIndexData).then(function(res) {
      console.log(res);
      wx.hideLoading();
      let temp = Object.assign({}, res.data);
      let startSpotList = [];
      if (temp.goData.length > 0) {
        startSpotList.push(temp.goData);
        startSpotList.push(temp.goData[0]['children']);
        startSpotList.push(temp.goData[0]['children'][0]['children'] || []);
      }
      that.setData({
        goData: temp.goData,
        destinationDate: temp.destinationDate,
        startSpotList: startSpotList,
        startSpotListPreview: startSpotList,
        endSpotList: [],
        endSpotListPreview: [],
        startSpot: [],
        endSpot: [],
        hotLineData: temp.hotLineData
      });
    })
  },

  // 点击目的地
  bindEndPickerTap(e) {
    if (this.data.endSpotList.length === 0) {
      wx.showToast({
        image: '../../../../images/center/7.png',
        title: '请先选择出发地',
      })
    }
  },

  // 选择地点
  bindSpotPickerChange(e) {
    // 类型,出发地还是目的地
    const type = e.currentTarget.dataset.type;
    // 出发地或目的地的列表
    const addressList = type + 'List';
    // 選擇的值
    let chooseData = e.detail.value;
    // 没改变的列默认会传null回来所以要转成0
    for (let i = 0; i < e.detail.value.length; i++) {
      if (chooseData[i] === null) {
        chooseData[i] = 0;
      }
    }
    // 因为picker显示的是一个长度为3的数组,对应3列,第2,3列会随着改变,所以需要保存一个当前选择的数组,才不会数据错乱
    this.setData({
      [type]: chooseData,
      [addressList]: this.data[addressList + 'Preview']
    })
    // 当改变的是出发地时,对应修改目的地的列表
    if (type === 'startSpot') {
      // 从目的地列表中找到出发地对应的目的地列表
      let temp = this.data['destinationDate'][this.data['goData'][this.data['startSpot'][0]]['code']];
      let endSpotList = [];
      if (temp.length > 0) {
        endSpotList.push(temp);
        endSpotList.push(temp[0]['children']);
        endSpotList.push(temp[0]['children'][0]['children'] || []);
      }
      this.setData({
        endSpotList: endSpotList,
        endSpotListPreview: endSpotList,
        endSpot: []
      })
    }
  },

  // 列变化时
  bindSpotPickerColumnChange(e) {
    const value = e.currentTarget.dataset.type;
    const type = e.currentTarget.dataset.type + 'Preview';
    const addressList = e.currentTarget.dataset.type + 'ListPreview'
    const data = {
      [addressList]: this.data[addressList],
      [type]: this.data[value].length !== 0 ? this.data[value] : [0, 0, 0]
    }
    data[type][e.detail.column] = e.detail.value;
    if (e.detail.column === 0) {
      data[addressList][1] = data[addressList][0][e.detail.value]['children'];
      data[addressList][2] = data[addressList][1][0]['children'] || [];
      data[type][1] = 0;
      data[type][2] = 0;
    } else if (e.detail.column === 1) {
      data[addressList][2] = data[addressList][1][e.detail.value]['children'] || [];
      data[type][2] = 0;
    }
    this.setData({
      [addressList]: data[addressList],
      [type]: data[type]
    })
  },

  // 交换起点终点
  bindExchangeSpot() {
    const startSpot = this.data.startSpot;
    const startSpotList = this.data.startSpotList;
    const startSpotListPreview = this.data.startSpotListPreview;
    const endSpot = this.data.endSpot;
    const endSpotList = this.data.endSpotList;
    const endSpotListPreview = this.data.endSpotListPreview;
    this.setData({
      startSpot: endSpot,
      startSpotList: endSpotList,
      startSpotListPreview: endSpotListPreview,
      endSpot: startSpot,
      endSpotList: startSpotList,
      endSpotListPreview: startSpotListPreview
    })
  },

  // 选择时间
  bindDateChange(e) {
    this.setData({
      date: e.detail.value,
      weekday: '星期' + app.utils.parseTime(new Date(e.detail.value), '{a}'),
    })
  },

  // 搜索
  bindSearch() {
    if (this.data['endSpotList'].length === 0) {
      app.showConfirm('提示', '请选择出发地,目的地~', false);
      return;
    }

    let lineId = null;

    let startSpotLineId = (this.data['startSpotList'][2].length === 0 ?
      this.data['startSpotList'][1][this.data['startSpot'][1]]['lineId'] :
      this.data['startSpotList'][2][this.data['startSpot'][2]]['lineId']);
    startSpotLineId = (startSpotLineId + '').split(',');

    let endSpotLineId = (this.data['endSpotList'][2].length === 0 ?
      this.data['endSpotList'][1][this.data['endSpot'][1]]['lineId'] :
      this.data['endSpotList'][2][this.data['endSpot'][2]]['lineId']);

    endSpotLineId = (endSpotLineId+'').split(',');

    lineId = endSpotLineId.filter(function (v) {
      return startSpotLineId.indexOf(v) !== -1 // 利用filter方法来遍历是否有相同的元素
    })

    lineId.join(',');

    if (lineId === null) {
      app.showConfirm('提示', '路线不存在,请重新选择~', false);
      return;
    }

    wx.navigateTo({
      url: '../timetable/timetable?lineId=' + lineId + '&chooseTime='+ this.data['date'],
    })
  },

  // 热门路线班次
  bindToTimetable(e) {
    wx.navigateTo({
      url: '../timetable/timetable?lineId=' + e.currentTarget.dataset.id + '&chooseTime=' + app.utils.parseTime(new Date(), '{y}-{m}-{d}')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initIcom();
  },

  initIcom() {
    this.setData({
      ticketIcon: app.globalData.config.ticketIcon
    })
    app.pageOnloadInit(this, app);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadData();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let wxappStyle = wx.getStorageSync('wxappStyle');
    return {
      title: app.globalData['wxappStyle']['wxappTitle'] || wxappStyle['wxappTitle'],
      path: '/pages/index/index'
    }

  }
})
